// Vue.filter('idToinfo', (friend_id)=>{
//     return vm.friendInfo[1].userImg
//         this.friendInfo.forEach((item, index)=>{
//             if(item._id == friend_id){
//                 console.log({
//                     note: item.name,
//                     userImg: item.userImg,
//                     userid: item.userid,
//                     _id: item._id
//                 }.userImg)
//                 return {
//                     note: item.name,
//                     userImg: item.userImg,
//                     userid: item.userid,
//                     _id: item._id
//                 }
                 
//             }
//         })
// })
Vue.filter('handleTime', (time)=>{
    return time1(time)
    function time1(t) {
        let s  = t.slice(0, 10)
        let year = Number(s.split('/')[0]) 
        let month = Number(s.split('/')[1])
        let day = Number(s.split('/')[2])
        //alert(year+" "+month+" "+day)
        let time1 = getDays(year, month, day) // 目标时间
        let time2 = getDays(vm.now.year, vm.now.month, vm.now.day) //参照时间
        if (year === vm.now.year) {//本年
            if (vm.now.year === year && vm.now.month === month && vm.now.day === day){ //当天
                return t.slice(11, 16) //只返回 时:分
            }else if (vm.now.year === year && time2 - time1 === 1) { //昨天(仅处理同年同月场景)
                return `昨天${t.slice(11, 16)}`  //返回 昨天+时:分
            }else if (vm.now.year === year && time2 - time1 > 1) {
                return t.slice(5, 16) //只返回 月/日 时:分
            }else{ //昨天以前
                return t.slice(5, 16) //只返回 月/日 时:分
            }
        }else{//往年
            return t.slice(0, 16) //返回完整时间 年/月/日 时:分
        } 
    }/**/
    function isfullyear(year){
        if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
            return true;
        }
    }
    function getDays(year, month, day){
        //把天数赋值给num
        var num = day;
        //如果用户输入1月 则直接返回天数
        if (month == 1) {
            return day;
        }
        var monthDay = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
        //循环遍历月份 循环条件是用户输入月份的前一个月份 
        for (var i = 0; i < month - 1; i++) {
            //num = 当月天数 + 之前每个月的天数
            num = num + monthDay[i]
        }
        //如果用户输入的年份是闰年并且输入的月份大于2 那么总天数加1
        if (isfullyear(year) && month > 2) {
            num++;
        }
        return num;
    }
})
var vm = new Vue({
    el: "section",
    data: {
        //header add
        isAddShow: false,
        search_value: "",
        showAction: false,
        userid: "",
        now: {},
        // msgList
        loading: true,
        msgList: [],
        friendMsgList: [],
        friendList: [],
        friendInfo: [],
        currentInfo: [],
        applicantList: [],
        active: 0
    },
    methods: {
        //添加
        addTab(){
            this.isAddShow = !this.isAddShow
            console.log(this.isAddShow)
        },
        select(index){
            let text = document.querySelector(`[index='${index}'] span.text`).innerText
            let href = ""
            switch (index) {
                case 0:
                    href = `./pages/createGroup/index.html`
                    window.location.href = href
                    break;
                
                case 1:
                    href = `./pages/addFriend/index.html`
                    window.location.href = href
                    break;
                
                case 2:
                    this.$toast({
                        message: `[${text}]功能暂未开放`,
                        forbidClick: true
                    });
                    break;
                
                case 3:
                    this.$toast({
                        message: `[${text}]功能暂未开放`,
                        forbidClick: true
                    });
                    break;
                
            }
        },
        closeNavBar(){
            if(this.isAddShow){
                this.isAddShow = false
            }else{
                console.log("navBar未唤起")
            }
        },
        // 切换消息/好友页面
        SwitchPage(){
            console.log("点击了帮友")
            let title2 = document.querySelector("header .title2")
            title2.style.pointerEvents = 'none'
            let section = document.querySelector("section")
            
            let duration = 800 // ms
            let delay = 100  //ms
            section.style.animation = `switchPage ${duration/1000}s ${delay/1000}s`
            // 翻转页面
            // section.style.transform='rotateY(180deg)'
            // section.style.transition='all'
            let timeout1 = duration+delay+50
            let timer1 = setTimeout(()=>{
                section.style.animation = `none`
                title2.style.pointerEvents = 'auto'
                // document.querySelector('section').style.transform='none'
                clearTimeout(timer1)
            }, timeout1)
            let timeout2 = 0.5*duration+delay
            let timer2 = setTimeout(()=>{
                if(this.active == 0){
                    this.active = 1
                }else if(this.active == 1){
                    this.active = 0
                }
                clearTimeout(timer2)
            },timeout2)
        },
        // 搜索框
        onSearch() {
            this.$toast(this.search_value);
        },
        onFocus() {
            this.showAction = true;
        },
        onCancel() {
            this.showAction = false;
        },
        // 群消息
        read(index, GroupID, GroupName, isRead){
            let hadNewMessage = !isRead
            let href = `./pages/GroupChat/index.html?GroupID=${GroupID}&GroupName=${GroupName}&hadNewMessage=${hadNewMessage}`
            window.location.href= href  
        },
        // 好友消息
        read2(index, friendid, read){
                let note = ""
                this.friendInfo.forEach((item, index)=>{
                    if(item._id == friendid){
                            note = item.name
                    }
                })
            console.log(note)
            let userID = friendid
            let href = `./pages/chat/index.html?userID=${userID}&note=${encodeURIComponent(note)}`
            window.location.href= href
        },
        newFriend(){
            if(this.applicantList.length == 0){
                this.$toast({
                    message: '暂无新的好友申请',
                    forbidClick: true
                })
            }else{
                window.location.href='./pages/newFriend/index.html'
            }
            
        },
        // 好友列表
        readFriend(index, userid){
            let href = `./pages/detail_user/index.html?userid=${userid}`
            window.location.href= href
        },
        idToinfo(friend_id){
            let info = {}
            this.friendInfo.forEach((item, index)=>{
                if(item._id == friend_id){
                    info = {
                        note: item.name,
                        userImg: item.userImg,
                        userid: item.userid,
                        _id: item._id
                    }
                }
            })
            return info
        }
    },
    mounted(){
        // 预加载音频
        let audio = new Audio();  
        // audio.src = 'https://downsc.chinaz.net/Files/DownLoad/sound1/202202/15370.mp3';
        audio.src = 'https://mp-737611d5-322c-418f-acde-af8355a0aa69.cdn.bspapp.com/audio/notice/7815.mp3';
        
        let date = new Date()
        let year = date.getFullYear()
        let month = date.getMonth()+1
        let day = date.getDate()
        this.now = {
            year: year,
            month: month,
            day: day
        }
        /**/
        let userInfo = localStorage.getItem('XGB-user')
        this.userid = JSON.parse(userInfo).id
        let url = `https://fc-mp-e8e2bde5-0c0c-4622-87b5-66f8b08c3856.next.bspapp.com/getArticleList1.0`
        let method = `getData_61rgh1vgbFD89167BVF`
        let data = {
            userid: this.userid
        }
        axios.post(`${url}/${method}`, data)
        .then(res=>{
            if(res.data.code === 0){
                // 未读在上，已读在下，已读和未读均按时间倒叙排列
                if(res.data.data.length == 0){
                    this.$toast({
                        message: '您未加入任何交流圈/群聊',
                        forbidClick: true,
                        duration: 3000
                    })
                }
                this.loading = false
                let msgList = res.data.data.groupMessageList
                let msgList_isRead = []
                let msgList_unRead = []
                for(let i=0; i<msgList.length; i++){
                    if(msgList[i].isRead){//已读
                        msgList_isRead = [...msgList_isRead, msgList[i]]
                    }else{//未读
                        msgList_unRead = [...msgList_unRead, msgList[i]]
                    }
                }
                msgList_isRead.sort(function(a, b) {  
                    return b.timestamp - a.timestamp;  
                })
                msgList_unRead.sort(function(a, b) {  
                    return b.timestamp - a.timestamp;  
                })
                msgList = [...msgList_unRead, ...msgList_isRead]
                this.msgList = msgList
                //好友消息
                //this.friendMsgList = res.data.data.friendMessage.msgList_final
                this.friendInfo = res.data.data.friendMessage.userInfo
                let friendMsgList = res.data.data.friendMessage.msgList_final
                let friendMsgList_isRead = []
                let friendMsgList_unRead = []
                for(let i=0; i<friendMsgList.length; i++){
                    if(friendMsgList[i].isRead){//已读
                        friendMsgList_isRead = [...friendMsgList_isRead, friendMsgList[i]]
                    }else{//未读
                        friendMsgList_unRead = [...friendMsgList_unRead, friendMsgList[i]]
                    }
                }
                friendMsgList_isRead.sort(function(a, b) {  
                    return b.timestamp - a.timestamp;  
                })
                friendMsgList_unRead.sort(function(a, b) {  
                    return b.timestamp - a.timestamp;  
                })
                friendMsgList = [...friendMsgList_unRead, ...friendMsgList_isRead]
                this.friendMsgList = friendMsgList
                let hadNewFriendMsg = false
                this.friendMsgList.forEach((item, index)=>{
                    if(!item.read) {
                        hadNewFriendMsg = true
                    }
                })
                // 有新的群消息或者好友消息
                if(msgList_unRead.length > 0 || hadNewFriendMsg) {
                    audio.play()
                    // 安卓震动
                    //Vibration接口用于在web浏览器中发出指令，让移动端设备振动。其中要判断是否支持此方法
                    function vibration() {
                        navigator.vibrate = navigator.vibrate || navigator.webkitVibrate || navigator.mozVibrate || navigator.msVibrate;
                        if (navigator.vibrate) {
                            return true;
                        }else{
                            return false;
                        }
                    }
                    //[震动时间，停止时间，震动时间，停止时间…] 
                    //[200,100,200, 200,100, 200.........]
                    if (vibration()==true){
                        navigator.vibrate([380,100]);
                    }else{
                        console.log("设备不支持震动")
                    }
                    // 安卓震动
                }
                // 加载好友列表
                method = `getFriend_A681746F4d1v4d6VNT7816`
                axios.post(`${url}/${method}`, data)
                .then(res=>{
                    if(res.data.code === 0){
                        this.friendList = res.data.data.data_friendList.sort((a, b) => a.note.localeCompare(b.note));
                        this.applicantList = res.data.data.data_applicantList
                        setTimeout(()=>{
                            let lis = document.querySelectorAll(".msgul li")
                            for(let i=0;i<lis.length; i++){
                                $(`.msgul li:nth-child(${i+1})`).on('touchstart', function(){
                                    $(`.msgul li:nth-child(${i+1})`).css('background', '#c3c3c352')
                                })
                                $(`.msgul li:nth-child(${i+1})`).on('touchend', function(){
                                    $(`.msgul li:nth-child(${i+1})`).css('background', '#fff')
                                })
                            }
                        }, 100)
                        //
                    }
                })
            }
            
        })
        
        
    }
})